# -*- coding: utf-8 -*-
# @Date   : 2020/3/3
# @File   : R68_comprehensiveCheck_OTO.py
# @Author : zhaochen
'''eof
name:综合校验
code:R68_comprehensiveCheck_OTO
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D,EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def FormatData(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        if eg in null_type_list:
            return None
        if isinstance(eg, list):
            return eg
        else:
            return None
    except:
        return None


# 统一转成datetime对象，只能转年月日的字符串
def date_format(str):
    import re
    r = re.compile(r'\D+')
    try:
        time = str[0:10]
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def factor1():
    """1.新增客户判定： if ratingRequest.occurType=="0101", factor1=0"""
    try:
        occur_type = ratingRequest.get("occurType")
        if occur_type == "0101":
            return 0
        else:
            return 1
    except:
        return None


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-12, 0]]
        return aaa
    except:
        return None


def factor2():
    """2.if 申请企业近1年内发生过法定代表人变更次数>0 then factor2= 0"""
    try:
        alter_list = FormatData("alterList")
        if alter_list is None:
            return u'缺失值'
        else:
            if len(alter_list) == 0:
                return 0
            else:

                change_list = [u"法人代表变更",u"负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更）",
                               u"法定代表人（负责人）变更",u"执行合伙企业事务的合伙人",u"法定代表人变更",u"法定代表人姓名",
                               u"负责人（法定代表人、首席代表、合伙事务执行人等）变更",u"法定代表人(负责人、董事长、首席代表)变更",u"负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）",
                               u"法定代表人（负责人、董事长、首席代表）变更",u"法定代表人",u"执行合伙企业事务的合伙",u"法定代表人(负责人、独资投资人)",
                               u"负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）变更",
                               u"负责人变更",u"法定代表人（负责人）",u"经营者姓名",u"负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更） "]

                result = set()
                flag = False
                date_list = get_date_list()
                for i in alter_list:
                    alt_item = i.get("altItem")
                    alt_date = date_format(i.get("altDate"))
                    if alt_date not in null_type_list and alt_item not in null_type_list:
                        flag = True
                        if date_list[0] < date_format(alt_date[0:10]) <= date_list[1] and alt_item in change_list:
                            result.add(alt_date+alt_item)
                if not flag:
                    return None
                else:
                    if len(result) > 0:
                        return 0
                    else:
                        return 1
    except:
        return None


def get_age(str1):
    try:
        date1 = datetime.now()
        date2 = date_format(str1)
        diff_year = date1.year - date2.year
        diff_month = date1.month - date2.month
        diff_day = date1.day - date2.day
        age = diff_year + diff_month/12.0 + diff_day/365.0
        return '%.4f' % age
    except:
        return u'缺失值'

def factor3():
    """3. if 年龄>55 then factor3=0：同【申请人年龄校验】策略"""
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    try:
        card_id = ratingRequest.get("legalPersonIdCard")
        if card_id not in null_type_list and len(card_id) == 18:
            birth = get_age(card_id[6:14])
            return 0 if birth > 55 else 1
        else:
            return None

    except:
        return None

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None or table == "":
            return [{}]
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return [{}]
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def PIMFormat():
    # 身份信息
    try:
        data = IC_DSJ_2D.get("data").get("PIM")[0].get("PB01")[0].get("PB01A")
        if data is None:
            return [{}]
        else:
            return data
    except:
        return [{}]

def PMMFormat():
    # 婚姻状况
    try:
        data = IC_DSJ_2D.get("data").get("PMM")[0].get("PB02")
        if data is None:
            return [{}]
        else:
            return data
    except:
        return [{}]


def identity():
    try:
        PB01A = PIMFormat()
        birthday = PB01A[0].get("PB01AR01")
        eduLevel = PB01A[0].get("PB01AD02") # 学历
        maritalState = PMMFormat() # 婚姻状况
        #
        registeredAddress = PB01A[0].get('PB01AQ03')
        if birthday in null_type_list and eduLevel in null_type_list and maritalState == [{}] and registeredAddress in null_type_list:
            return 1
        else:
            return 0
    except:
        return u'缺失值'


def creditQue():
    data = IC_DSJ_2D['data']
    try:
        PCO = getTable(data, 'PCO', 1)
        if PCO is None:
            return u'缺失值'
        elif PCO == [{}]:
            return 1
        else:
            PC02 = getTable(PCO[0], 'PC02', 0)
            if PC02 is None:
                return u'缺失值'
            elif PC02 == [{}]:
                return 1
            else:
                PC02A = getTable(PC02[0], 'PC02A', 0)
                if PC02A is None:
                    return u'缺失值'
                elif PC02A == [{}]:
                    return 1
                else:
                    PC02AH = getTable(PC02A[0], 'PC02AH', 1)
                    if PC02AH is None:
                        return u'缺失值'
                    elif PC02AH == [{}]:
                        return 1
                    else:
                        factor = []
                        for i in PC02AH:
                            firstMonth = i.get('PC02AR01')
                            if firstMonth in null_type_list:
                                factor.append(None)
                            else:
                                factor.append(firstMonth)
                        if len(set(factor)) == 1 and None in factor:
                            return 1
                        else:
                            return 0
    except:
        return u'缺失值'




def IC26_WhiteUser():
    '''1.身份信息表中，生日、婚姻状况、学历、注册地址全为空
        2.信用提示表中，首笔贷款发放月份、首张贷记卡发卡月份、首张准贷记卡发卡月份全为空
        若上述2条任一满足则为个人征信白户'''

    factor1 = identity()
    factor2 = creditQue()
    if factor1 == u'缺失值' or factor2 == u'缺失值':
        factor = None
    else:
        if factor1 or factor2:
            factor = 1 # 个人征信白户
        else:
            factor = 0
    if factor:
        return 1
    else:
        return 0



def EC09_WhiteUser():
    try:
        data = EC_DSJ_2D['data']
        EBA = getTable(data, 'EBA', 1)
        if EBA is None:
            factor = 1
        elif EBA == [{}]:
            factor = 1
        else:
            EB01 = getTable(EBA[0], 'EB01', 1)
            if EB01 is None or EB01 == [{}]:
                factor = 1
            else:
                EB01A = getTable(EB01[0], 'EB01A', 0)
                if EB01A is None or EB01A == [{}]:
                    factor = 1
                else:
                    firstLoanYear = EB01A[0].get('EB01AR01')
                    if firstLoanYear in null_type_list:
                        factor = 1
                    else:
                        factor = 0
        if factor:
            return 1
        else:
            return 0
    except:
        return None


def factor4():
    """if  个人征信白户= True  or 企业征信白户 = True  ,factor4 =0"""
    ic_white = IC26_WhiteUser()
    ec_white = EC09_WhiteUser()
    if ic_white is None and ec_white is None:
        return None
    else:
        if ic_white or ec_white:
            return 0
        else:
            return 1



def R68_comprehensiveCheck_OTO():
    f1 = factor1()
    f2 = factor2()
    f3 = factor3()
    f4 = factor4()
    if f1 is None and f2 is None and f3 is None and f4 is None:
        return u'缺失值'
    else:
        if f1 == 0 and f2 == 0 and f3 == 0 and f4 == 0:
            return 0
        else:
            return 1


result = R68_comprehensiveCheck_OTO()
